<template>
    <div class="order">
        <van-nav-bar title="填写订单信息" left-text="返回" left-arrow @click-left="goback" />
        <van-cell-group>
            <van-cell v-if="checkedAddress" isLink @click="goAddressList()" title="收货地址">
                <div slot="label">
                    <div>
                        <span>{{ checkedAddress.name }} </span>
                        <span>{{ checkedAddress.mobile }} </span>
                    </div>
                    <div>
                        {{ checkedAddress.province+checkedAddress.city+checkedAddress.region+checkedAddress.detailAddress }}
                    </div>
                </div>
            </van-cell>
        </van-cell-group>

        <van-cell-group>
            <van-cell class="order-coupon" title="优惠券" is-link :value="getCouponValue()" @click="getCoupons"/>
        </van-cell-group>

        <!-- 优惠券列表 -->
        <van-popup v-model="showList" position="bottom">
            <van-coupon-list
                    :coupons="coupons"
                    :chosen-coupon="chosenCoupon"
                    :disabled-coupons="disabledCoupons"
                    @change="onChange"
                    @exchange="onExchange"
            />
        </van-popup>

        <van-card
                v-for="item in checkedGoodsList"
                :key="item.id"
                :title="item.name"
                :num="item.quantity"
                :price="item.price"
                :thumb="item.headPic"
        >
            <div slot="desc">
                <div class="van-card__desc">
                    <van-tag plain style="margin-right:6px;" v-for="(spec, index) in item.specifications" :key="index">
                        {{spec}}
                    </van-tag>
                </div>
            </div>
        </van-card>

        <van-cell-group>
            <van-cell title="商品金额">
                <span class="red">{{goodsTotalPrice * 100 | yuan}}</span>
            </van-cell>
            <van-cell title="邮费">
                <span class="red">{{ freightPrice * 100| yuan}}</span>
            </van-cell>
            <van-cell title="优惠券">
                <span class="red">-{{ couponPrice * 100| yuan}}</span>
            </van-cell>
            <van-field v-model="message" placeholder="请输入备注" label="订单备注">
                <template slot="icon">{{message.length}}/50</template>
            </van-field>
        </van-cell-group>

        <van-submit-bar
                :price="actualPrice*100"
                label="总计："
                buttonText="提交订单"
                :disabled="isDisabled"
                @submit="onSubmit"
        />
    </div>
</template>

<script>
    import {Card, Tag, ard, Field, SubmitBar, Toast,NavBar} from 'vant';
    import {CouponCell, CouponList, Popup} from 'vant';
    import {cartCheckout, orderSubmit, couponSelectList, submitGoodsList,addressDetail,wxConfig} from '@/api/api';
    import {getLocalStorage, setLocalStorage, removeLocalStorage} from '@/utils/local-storage';
    import wx from 'weixin-js-sdk'
    import _ from 'lodash';
    import dayjs from 'dayjs';

    export default {
        data() {
            return {
                checkedGoodsList: [],
                checkedAddress: {
                    name:"",
                    mobile:"",
                    province:"",
                    city:"",
                    region:"",
                    detailAddress:"",
                },
                availableCouponLength: 0, // 可用的优惠券数量
                goodsTotalPrice: 0, //商品总价
                freightPrice: 0, //快递费
                selectCouponId:-1, //选择的优惠券ID
                couponPrice: 0, //优惠券的价格
                grouponPrice: 0, //团购优惠价格
                orderTotalPrice: 0, //订单总价
                actualPrice: 0, //实际需要支付的总价
                message: '',

                isDisabled: false,
                showList: false,
                chosenCoupon: -1,
                coupons: [],
                disabledCoupons: []
            };
        },
        created() {
            this.init();
        },
        mounted() {
            var currentUrl=escape(window.location.href);
            wxConfig({url: currentUrl}).then(res => {
                var config = res.data.result;
                wx.config({
                    beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
                    appId: config.appId, // 必填，企业微信的corpID
                    timestamp: config.timestamp, // 必填，生成签名的时间戳
                    nonceStr: config.nonceStr, // 必填，生成签名的随机串 必填，生成签名的随机串
                    signature: config.signature, // 必填，签名
                    jsApiList: ['chooseWXPay']
                });
            });

        },


        methods: {
            goback() {
                this.$router.go(-1);
            },
            onSubmit() {
                var This=this;
                const {AddressId} = getLocalStorage('AddressId');
                if (AddressId === null) {
                    Toast.fail('请设置收货地址');
                    return;
                }
                const orderItem=[];
                var couponId;
                _.each(This.checkedGoodsList, v => {
                    orderItem.push({productId:v.id,productPrice:v.price,productQuantity:v.quantity});
                });

                if(This.selectCouponId!=-1){
                    couponId=This.selectCouponId;
                }
                this.isDisabled = true;
                orderSubmit({
                    memberReceiveAddress: AddressId,
                    useIntegration:0,
                    couponId:couponId,
                    freightPrice:This.freightPrice,
                    couponPrice:This.couponPrice,
                    totalPrice:(This.goodsTotalPrice+This.freightPrice) ,
                    payPrice: This.actualPrice,
                    orderItem:orderItem,
                    note: this.message
                }).then(res => {
                    // 下单成功，重置下单参数。
                    var datas=res.data.result;
                    wx.invoke('getBrandWCPayRequest',{
                        // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。
                        // 但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                        timeStamp: datas.timeStamp,
                        // 支付签名随机串，不长于 32 位
                        nonceStr: datas.nonceStr,
                        package: datas.packageValue, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                        signType: datas.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                        paySign: datas.paySign, // 支付签名
                        success: function(res) {
                            // 支付成功后的回调函数
                            this.$toast("支付成功");
                            this.$router.push({ path: '/order/payment/2' });
                        },
                        fail: function(res) {
                            this.$toast("支付失败");
                            this.$router.push({ path: '/order/payment/1' });
                        },
                        complete: function(res) {
                            this.$toast("complete");
                            this.$router.push({ path: '/order/payment/2' });
                        }
                    })
                }).catch(error => {
                    this.$router.push({ path: '/order/payment/1' });
                    this.isDisabled = false;
                    this.$toast(error);
                })
            },
            goAddressList() {
                setLocalStorage({ checkoutRouter: 1 });
                this.$router.push({
                    path: '/user/address'
                });
            },
            getCouponValue() {
                if (this.couponPrice !== 0) {
                    return "-¥" + this.couponPrice + ".00元"
                }
                if (this.availableCouponLength !== 0) {
                    return this.availableCouponLength + "张可用"
                }
                return '选择优惠券'
            },
            getCoupons() {
                couponSelectList({status: 0, pageNo: 1,pageSize:10}).then(res => {
                    var cList = res.data.result;
                    this.coupons = []
                    this.disabledCoupons = [];
                    for (var i = 0; i < cList.length; i++) {
                        var c = cList[i]
                        var coupon = {
                            id: c.id,
                            cid: c.cid,
                            name: c.name,
                            condition: '满' + c.price + '元可用',
                            value: c.price,
                            description: c.note,
                            startAt: new Date(c.useStartTime).getTime() / 1000,
                            endAt: new Date(c.overdueTime).getTime() / 1000,
                            // valueDesc: c.price,
                            unitDesc: '元'
                        }
                        if (c.useStatus==0) {
                            this.coupons.push(coupon);
                        } else {
                            this.disabledCoupons.push(coupon);
                        }
                    }
                    this.showList = true
                })
            },
            reCalculatePrice(){
                this.actualPrice=(this.goodsTotalPrice+this.freightPrice-this.couponPrice).toFixed(2);
            },
            init() {
                const This = this;
                const addressId = getLocalStorage('AddressId');
                if(addressId){
                    addressDetail({id: addressId.AddressId}).then(res => {
                        This.checkedAddress=res.data.result;
                    });
                }
                const {submitProductIds, submitQuantity} = getLocalStorage("submitProductIds","submitQuantity");
                const quantitys = submitQuantity.split(",");
                submitGoodsList({productIds: submitProductIds}).then(res => {
                    This.checkedGoodsList = res.data.result;
                    for(var i = 0; i < This.checkedGoodsList .length; i++) {
                        This.checkedGoodsList[i].quantity=quantitys[i];
                        This.goodsTotalPrice+=quantitys[i]*This.checkedGoodsList[i].price;
                    }
                    This.reCalculatePrice();
                });

            },
            onChange(index) {
                var This=this;
                this.showList = false;
                this.chosenCoupon = index;
                for(var i = 0; i < This.coupons.length; i++){
                    if(index===-1){
                        This.selectCouponId="";
                        This.couponPrice=0;
                        This.reCalculatePrice();
                        return false;
                    }
                    else if(index===i){
                        if(this.goodsTotalPrice+this.freightPrice-This.coupons[i].value<=0){
                            this.$toast('订单价格不能为0');
                        }else{
                            This.selectCouponId=This.coupons[i].id;
                            This.couponPrice=This.coupons[i].value;
                            This.reCalculatePrice();
                        }
                        return false;
                    }
                }
            },
            onExchange() {
                this.$toast("兑换暂不支持");
            }
        },
        components: {
            [NavBar.name]: NavBar,
            [Toast.name]: Toast,
            [SubmitBar.name]: SubmitBar,
            [Card.name]: Card,
            [Field.name]: Field,
            [Tag.name]: Tag,
            [CouponCell.name]: CouponCell,
            [CouponList.name]: CouponList,
            [Popup.name]: Popup
        }
    };
</script>


<style lang="scss" scoped>
    .order-coupon {
        margin-top: 10px;
    }
</style>